package com.drugStorage.struts.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.drugStorage.domain.User;
import com.drugStorage.spring.service.UserService;
import com.drugStorage.struts.actionForms.LoginActionForm;

public class LoginAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		LoginActionForm laf = (LoginActionForm) form;
		String name = laf.getName();
		String password = laf.getPassword();
		String userType = laf.getUserType();
		BeanFactory factory = new ClassPathXmlApplicationContext(
				"applicationContext-*.xml");
		UserService userService = (UserService) factory
				.getBean("UserService");
		User user = userService.findByName(name);
		if (user.getPassword().equals(password)
				&& user.getUserType().equals(userType)) {

			{
				if (user.getUserType().equals("dean"))
					return mapping.findForward("dean");
				else if (user.getUserType().equals("DrugManager"))
					return mapping.findForward("DrugManager");
				else if (user.getUserType().equals("Buyer"))
					return mapping.findForward("Buyer");
				else if (user.getUserType().equals("Accountant"))
					return mapping.findForward("Accountant");
				else if(user.getUserType().equals("SystemAdmin"))
					return mapping.findForward("SystemAdmin");
				else
					return mapping.findForward("loginerror");
			}
		} else
			return mapping.findForward("loginerror");
	}

}
